package com.datamation.swadeshi.view;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.control.ReferenceNum;
import com.datamation.swadeshi.control.Toast;
import com.datamation.swadeshi.control.data.DebtorDS;
import com.datamation.swadeshi.control.data.OrdHedDS;
import com.datamation.swadeshi.control.data.RouteDS;
import com.datamation.swadeshi.control.data.SalRepDS;
import com.datamation.swadeshi.control.data.SharedPreferencesClass;
import com.datamation.swadeshi.model.OrdHed;

public class FragmentSalesManagementPreSalesSAHeader extends Fragment implements OnClickListener{
	
	View view;
	TextView customerName,outStandingAmt,lastBillAmt;
	EditText orderNo,currnentDate,route,manual,remarks;
	Button selectItem,deliveryDate;
	//ReferenceNum referenceNum;
	Toast  toast;
	public static final String SETTINGS = "SETTINGS";
	public static SharedPreferences localSP;
	//public static String sdelDate="",sManual="",sRemarks="";
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		view = inflater.inflate(R.layout.sales_management_pre_sales_header, container, false);
		MainActivity activity =(MainActivity) getActivity();
		
		SetTitleAdapter adapter =new SetTitleAdapter();
		adapter.createCutomActionBarTitle("Order Header", getActivity());
		
		toast = new Toast();
		
		customerName = (TextView) view.findViewById(R.id.customerName);
		outStandingAmt = (TextView) view.findViewById(R.id.sa_header_outstanding_amt);
		lastBillAmt = (TextView) view.findViewById(R.id.sa_header_last_bill_amt);
		
		orderNo=(EditText) view.findViewById(R.id.sa_header_order_no);
		currnentDate=(EditText) view.findViewById(R.id.sa_header_date);
		route=(EditText) view.findViewById(R.id.sa_header_route);
		manual=(EditText) view.findViewById(R.id.sa_header_manual_no);
		remarks =(EditText) view.findViewById(R.id.sa_header_remark);
		
		selectItem = (Button) view.findViewById(R.id.button3);
		deliveryDate=(Button) view.findViewById(R.id.sa_header_del_date);
		
		//button fonts changing code
		Typeface tf = Typeface.createFromAsset(activity.getAssets(),"fonts/coopbl.ttf");
		selectItem.setText("Select Items >>");
		selectItem.setTypeface(tf);
		
		currentDate();
		
		localSP = activity.getSharedPreferences(SETTINGS,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
		
		ReferenceNum referenceNum=new  ReferenceNum(getActivity());
		
		orderNo.setText(referenceNum.getCurrentRefNo(getResources().getString(R.string.NumVal)));
		
	
		OrdHedDS hedDS =new OrdHedDS(getActivity());
		ArrayList<OrdHed> getOrdHed = hedDS.getAllActiveOrdHed(referenceNum.getCurrentRefNo(getResources().getString(R.string.NumVal)));
		
		if(!getOrdHed.isEmpty()){
			
			for (OrdHed ordHed : getOrdHed)
			{
								
				deliveryDate.setText(ordHed.getFORDHED_DELV_DATE());
				manual.setText(ordHed.getFORDHED_MANU_REF());
				remarks.setText(ordHed.getFORDHED_REMARKS());
				
				activity.selectedOrdHed=ordHed;
				
				if(activity.selectedDebtor==null){
					DebtorDS debtorDS =new DebtorDS(getActivity());
					activity.selectedDebtor=debtorDS.getSelectedCustomerByCode(ordHed.getFORDHED_DEB_CODE());
				}
			}
			
		}else{
			
			try {
				if(activity.selectedOrdHed !=null)
				{
					deliveryDate.setText(activity.selectedOrdHed.getFORDHED_DELV_DATE());
					manual.setText(activity.selectedOrdHed.getFORDHED_MANU_REF());
					remarks.setText(activity.selectedOrdHed.getFORDHED_REMARKS());
				}
			}catch (Exception e){
				Log.v("Exception Selected OrdHed ", e.toString());
			}
			
		}
		
		
		selectItem.setOnClickListener(this);
		deliveryDate.setOnClickListener(this);
		
	
		
		///------ testing amount---------
		outStandingAmt.setText(String.format("%,.2f", 20000003439.51));
		lastBillAmt.setText(String.format("%,.2f", 20000003439.51));
		/// -----------------------------
		
		try{
			//MainActivity activity =(MainActivity) getActivity();
			if(activity.selectedDebtor !=null)
			{
				RouteDS routeDS = new  RouteDS(getActivity());
				customerName.setText(activity.selectedDebtor.getFDEBTOR_NAME());
				route.setText(routeDS.getRouteNameByCode(activity.selectedDebtor.getFDEBTOR_CODE()));
			}else{
			
				toast.createToastMessage("Please select a customer", getActivity());
				getActivity().getActionBar().setSelectedNavigationItem(0);
			}
		}catch (NumberFormatException e){
			getActivity().getActionBar().setSelectedNavigationItem(0);
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}
		
		return view;
	}
	
	
	public void datetimepicker()
	{		
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.date_picker);
		final DatePicker dtp  = (DatePicker)dialog.findViewById(R.id.dpResult);
		dialog.setCancelable(true);
		Button button = (Button)dialog.findViewById(R.id.btnok);	
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
			int month = dtp.getMonth()+1;
			int year = dtp.getYear();
			int date = dtp.getDayOfMonth();
			deliveryDate.setText(year+"-0"+month+"-"+date);
			//sdelDate=year+"/0"+month+"/"+date;
			dialog.dismiss();
				
			}
		});
				
		dialog.show();
	}
		

	private void currentDate() {
		// TODO Auto-generated method stub
		//current date and time 
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = new Date();
				currnentDate.setText(dateFormat.format(date));
				deliveryDate.setText(dateFormat.format(date));
	}
	
	private String currentTime(){
		Calendar cal = Calendar.getInstance();
    	cal.getTime();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
    	return sdf.format(cal.getTime());
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button3://next
		
			if(!customerName.getText().toString().equals("") && 
					!orderNo.getText().toString().equals("") &&	!route.getText().toString().equals("")){
				
				//referenceNum.nNumValueInsertOrUpdate("EXPR");
				
				MainActivity activity = (MainActivity) getActivity();
				RouteDS routeDS = new  RouteDS(getActivity());
				SalRepDS repDS=new SalRepDS(activity);
				OrdHed hed =new OrdHed();
				
				if(activity.selectedOrdHed !=null)
					hed =activity.selectedOrdHed;//set already enter values objects
				
				hed.setFORDHED_REFNO(orderNo.getText().toString());
				hed.setFORDHED_DEB_CODE(activity.selectedDebtor.getFDEBTOR_CODE());
				hed.setFORDHED_ADD_DATE(currnentDate.getText().toString());
				hed.setFORDHED_DELV_DATE(deliveryDate.getText().toString());
				hed.setFORDHED_ROUTE_CODE(routeDS.getRouteCodeByRoute(route.getText().toString()));
				hed.setFORDHED_MANU_REF(manual.getText().toString());
				hed.setFORDHED_REMARKS(remarks.getText().toString());
				hed.setFORDHED_ADD_MACH(localSP.getString("MAC_Address", "No MAC Address").toString());
				hed.setFORDHED_ADD_USER(repDS.getCurrentRepCode());
				hed.setFORDHED_APP_DATE("9999-12-31");
				hed.setFORDHED_APPSTS("1");
				hed.setFORDHED_APP_USER(repDS.getCurrentRepCode());
				hed.setFORDHED_CUR_CODE("LKR");
				hed.setFORDHED_CUR_RATE("1.00");
				hed.setFORDHED_IS_ACTIVE("1");
				hed.setFORDHED_LOC_CODE(repDS.getCurrentRepCode());
				
				activity.selectedOrdHed = hed;//new updated object (new data + already enter data)
				
				SharedPreferencesClass.setLocalSharedPreference(activity, "SO_Start_Time",currentTime());
				
				ArrayList<OrdHed> ordHedList=new ArrayList<OrdHed>();
				OrdHedDS ordHedDS =new  OrdHedDS(getActivity());
				//head
				ordHedList.add(activity.selectedOrdHed);
				if(ordHedDS.createOrUpdateOrdHed(ordHedList)>0)
				   getActivity().getActionBar().setSelectedNavigationItem(2);
				
			}
		break;
		
		case R.id.sa_header_del_date:
			datetimepicker();
			break;
		default:
			break;
		}
	}
	

}
